package cn.cool.interceptors;

import cn.cool.utils.JWTUtils;
import cn.cool.utils.RedisUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LiuH
 * @create 2021-01-24 下午 4:51
 */
public class JWTLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("token");
        Map<String, Object> map = new HashMap<>();
        try {
            //验证token
            JWTUtils.verify(token);
            //取出 userid
            DecodedJWT verify = JWTUtils.getValue(token);
            String userId = verify.getClaim("userId").asString();
            //取出redis中对应的 token
            String redisToken = (String) redisUtil.get("token:" + userId);
            //比较 token
            if (!StringUtils.isEmpty(token) && token.equals(redisToken)){
                return true;
            }
        }
        catch (SignatureVerificationException e) {
            map.put("message", "签名不一致");
        } catch (TokenExpiredException e) {
            map.put("message", "凭证已过期,请重新登录");
        } catch (AlgorithmMismatchException e) {
            map.put("message", "算法不匹配");
        } catch (InvalidClaimException e) {
            map.put("message", "失效的payload");
        } catch (Exception e) {
            map.put("message", "token无效");
        }

        map.put("state", false);
       // map.put("message", "请先登录!");
        //响应到前台: 将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
